package com.cq.hd.base;

import com.alibaba.fastjson.JSON;
import com.cq.hd.common.annotation.MerchantLoginUser;
import com.cq.hd.common.constant.RedisKeyConstant;
import com.cq.hd.common.entity.MerchantAppLoginUser;
import com.cq.hd.common.entity.MerchantUserInfo;
import com.cq.hd.common.utils.JwtUtil;
import com.cq.hd.common.utils.RedisUtil;
import com.cq.hd.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Configuration
public class MerchantLoginUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private RedisUtil redisUtil;

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(MerchantLoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        MerchantAppLoginUser merchantAppLoginUser = new MerchantAppLoginUser();
        String token = webRequest.getHeader("Authorization");
        if (StringUtils.isNullOrEmpty(token)) {
            return merchantAppLoginUser;
        }
        Long userId = Long.valueOf(JwtUtil.getAudience(token, 0));
        merchantAppLoginUser.setMerchantId(userId);
        String userInfoRedis = redisUtil.get(String.format(RedisKeyConstant.MERCHANT_INFO_KEY, userId));
        if (!StringUtils.isNullOrEmpty(userInfoRedis)) {
            MerchantUserInfo userInfo = JSON.parseObject(userInfoRedis, MerchantUserInfo.class);
            merchantAppLoginUser.setMerchantUserInfo(userInfo);
        }
        return merchantAppLoginUser;
    }
}
